// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode')

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed

/**
 * @param {vscode.ExtensionContext} context
 */
function activate(context) {
  // Use the console to output diagnostic information (console.log) and errors (console.error)
  // This line of code will only be executed once when your extension is activated
  console.log('Congratulations, your extension "UpdateTime" is now active!')

  // 这个命令必须在 package.json 里面定义
  // 通过这个registerCommand方法，传入的两个参数分别是 命令名（和package.json里注册的要一样） 和该命令的回调函数
  let updateTime = vscode.commands.registerCommand(
    'MyMarkdownPlugin.updateMarkdownTime',
    function () {
      let editor = vscode.window.activeTextEditor
      // editor 是否为 undefined，是的话就结束命令的运行。
      if (!editor) {
        return
      }

      let flag = 0
      // 逐行读取，直到读到updated为止
      for (let index = 0; index < 35; index++) {
        if (editor.document.lineAt(index).text.indexOf('updated') != -1) {
          flag = index
          break
        }
      }

      let timeStr = 'updated: ' + getTimeStr()

      // 修改原本的那行，使用edit的api edit的参数是一个回调函数(会传入一个TextEditorEdit)
      editor.edit((editBuilder) => {
        // 替换为timeStr
        editBuilder.replace(editor.document.lineAt(flag).range, timeStr)
      })

      // js的 ${} 是可以在模板 字符串 中包含表达式
      vscode.window.showInformationMessage('Update to: ' + timeStr)
    }
  )

  // 自动添加一个顶部栏
  let insertColumn = vscode.commands.registerCommand(
    'MyMarkdownPlugin.insertMarkdownColumn',
    () => {
      let editor = vscode.window.activeTextEditor
      // editor 是否为 undefined，是的话就结束命令的运行。
      if (!editor) return

      const config = vscode.workspace.getConfiguration();

      // 取得文件名
      let fileName = editor.document.fileName.substring(
        editor.document.fileName.lastIndexOf('\\') + 1,
        editor.document.fileName.lastIndexOf('.')
      )


      let url = '';
      if (config.get('markdown.isRandom')) {
        url = getRandomUrl()
      }

      // 组合信息
      let str =
        '---\n' +
        `title: ${fileName}\n` +
        `date: ${getTimeStr()}\n` +
        'tags: []\n' +
        'categories: []\n' +
        `updated: ${getTimeStr()}\n` +
        `cover: ${url}\n` +
        '---\n'

      vscode.window.showInformationMessage('Insert the success !')

      // 插入信息到第一行
      editor.edit((editBuilder) => {
        // 从0开始插入
        editBuilder.replace(editor.document.lineAt(0).range, str)
      })
    }
  )

  /* 添加一次性的命令，当该拓展停用，
		 在subscriptions里注册的命令都失效
		（subscriptions是个数组）
	*/
  context.subscriptions.push(updateTime, insertColumn)
}
exports.activate = activate

// 获取当前时间 返回格式：2020-06-29 19:16:49
function getTimeStr() {
  let datetime = new Date()
  let year = datetime.getFullYear()
  let month = datetime.getMonth()
  let date = datetime.getDate()
  let hour = datetime.getHours()
  let minute = datetime.getMinutes()
  let second = datetime.getSeconds()

  return (
    year +
    '-' +
    (month + 1 >= 10 ? month + 1 : '0' + (month + 1)) +
    '-' +
    (date + 1 < 10 ? '0' + date : date) +
    ' ' +
    (hour + 1 < 10 ? '0' + hour : hour) +
    ':' +
    (minute + 1 < 10 ? '0' + minute : minute) +
    ':' +
    (second + 1 < 10 ? '0' + second : second)
  )
}

function getRandomUrl() {

  const config = vscode.workspace.getConfiguration();
  const imgArr = config.get('markdown.imgArr'); // 获取指定配置项

  let num = Math.floor(Math.random() * imgArr.length)
  return imgArr[num]
}


// this method is called when your extension is deactivated
function deactivate() {}

module.exports = {
  activate,
  deactivate,
}
